package com.yuandengta.yomall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yuandengta.common.constant.ProductConstant;
import com.yuandengta.yomall.product.dao.AttrAttrgroupRelationDao;
import com.yuandengta.yomall.product.dao.AttrGroupDao;
import com.yuandengta.yomall.product.dao.CategoryDao;
import com.yuandengta.yomall.product.entity.AttrAttrgroupRelationEntity;
import com.yuandengta.yomall.product.entity.AttrGroupEntity;
import com.yuandengta.yomall.product.entity.CategoryEntity;
import com.yuandengta.yomall.product.service.CategoryService;
import com.yuandengta.yomall.product.vo.AttrGroupRelationVO;
import com.yuandengta.yomall.product.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.product.dao.AttrDao;
import com.yuandengta.yomall.product.entity.AttrEntity;
import com.yuandengta.yomall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存规则参数
     * @param attrVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrVO attrVO) {
        // 保存基本属性
        AttrEntity attrEntity = new AttrEntity();
        // 属性拷贝
        BeanUtils.copyProperties(attrVO, attrEntity);
        this.save(attrEntity);

        // 保存关联关系 - 基本属性（只有规格参数需要和属性分组建立关系，销售属性不建立关系）
        if (attrVO.getAttrType() == ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()
                && attrVO.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            relationDao.insert(relationEntity);
        }
    }

    /**
     * 查询规格参数和销售属性列表
     * @param params 分页信息和查询关键字key
     * @param catelogId 三级分类ID
     * @param attrType 属性类型
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType)
                        ? ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.attrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        // 从分页对象中获取查询记录集
        List<AttrEntity> records = page.getRecords();
        List<AttrVO> attrVOList = records.stream().map(attrEntity -> {
            AttrVO attrVO = new AttrVO();
            // 属性拷贝
            BeanUtils.copyProperties(attrEntity, attrVO);

            // 查询并设置分组名 groupName，基本属性需要显示分组，销售属性没有属性分组
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            // 查询并设置分类名 catelogName
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrVO.setCatelogName(categoryEntity.getName());
            }

            return attrVO;
        }).collect(Collectors.toList());

        pageUtils.setList(attrVOList);

        return pageUtils;
    }

    /**
     * 获取规格参数信息
     * @param attrId 属性id
     * @return 规格参数VO对象
     */
    @Cacheable(value = {"attr"}, key = "'attrInfo:'+#root.args[0]")
    @Override
    public AttrVO getAttrInfo(Long attrId) {
        AttrVO attrVO = new AttrVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrVO);

        // 查询并设置所属分组信息，只有基本属性才有属性分组
        if (attrVO.getAttrType() == ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                attrVO.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 查询并设置所属分类信息
        // 一个微服务内部，service之间调用没有问题，考虑到开发便捷性和代码重用
        // 对于是否违背设计原则，高内聚低耦合，本身微服务划分从根本上就已经做到了高内聚低耦合
        // [2, 34, 225]
        Long[] categoryPath = categoryService.findCategoryPath(attrEntity.getCatelogId());
        attrVO.setCatelogPath(categoryPath);
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrVO.setCatelogName(categoryEntity.getName());
        }

        return attrVO;
    }

    /**
     * 修改规格参数
     * @param attrVO
     */
    @CacheEvict(value = {"attr"}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAttr(AttrVO attrVO) {
        // 修改基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        this.updateById(attrEntity);

        // 修改属性分组关联 - 基本属性
        if (attrVO.getAttrType() == ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            relationEntity.setAttrId(attrVO.getAttrId());

            Integer count = relationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId()));
            if (count > 0) {
                // 修改关联关系
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVO.getAttrId()));
            } else {
                // 新增关联关系
                relationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据属性分组id查找关联的所有基本属性（规格参数）
     * @param attrgroupId 属性分组ID
     * @return 当前属性分组的属性集合
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        // 从 pms_attr_attrgroup_relation 表中查找指定的属性分组
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrgroupId));

        // 根据属性分组查找到所有的属性ID
        List<Long> attrIds = relationEntities.stream().map(relationEntity -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());

        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }

        // 批量查找所有的属性
        List<AttrEntity> attrEntities = this.listByIds(attrIds);

        return attrEntities;
    }

    /**
     * 删除属性与属性分组关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map(relationVO -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relationVO, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        relationDao.deleteRelation(entities);
    }

    /**
     * 获取当前属性分组未关联的所有属性
     * @param params 分页参数和查询关键字key
     * @param attrgroupId 属性分组ID
     * @return 没有关联分组的属性集合
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        // 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 当前分组只能关联别的分组没有引用的属性
        // 1. 查找当前分类下的所有属性分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId));
        List<Long> attrGroupIds = attrGroupEntities.stream().map(groupEntity -> {
            return groupEntity.getAttrGroupId();
        }).collect(Collectors.toList());

        // 2. 查找分组关联的所有属性id
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", attrGroupIds));
        List<Long> attrIds = relationEntities.stream().map(relationEntity -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());

        // 3. 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.attrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        // 若带有查询条件，则需要拼装查询语句
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    /**
     * 在指定的属性集合里面，查找出能够被检索的属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}